package com.wg.net.server.tcp.init;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wg.net.NetConfig;
import com.wg.net.server.tcp.handle.WebsocketServerHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * WebSocket协议初始化处理器（负责WebSocket连接的处理器链初始化）
 *
 * @author 少爷123
 */
public class WebsocketInitializeHandler implements InitializeHandler {
    private static final Log log = LogFactory.get();

    // 从配置获取最大内容长度
    private final int maxContentLength = NetConfig.getInstance().getMaxContentLength();

    @Override
    public void handle(ChannelHandlerContext ctx) throws Exception {
        log.debug("开始初始化WebSocket连接处理器链...");
        ChannelPipeline pipeline = ctx.pipeline();

        try {
            // 1. 添加HTTP基础编解码器（WebSocket基于HTTP握手）
            pipeline.addLast("http-codec", new HttpServerCodec());

            // 2. 添加分块写处理器（支持大文件传输）
            pipeline.addLast("chunked-write", new ChunkedWriteHandler());

            // 3. 添加HTTP消息聚合器（聚合HTTP请求/响应）
            pipeline.addLast("http-aggregator", new HttpObjectAggregator(maxContentLength));

            // 4. 添加WebSocket帧聚合器（聚合WebSocket帧）
            pipeline.addLast("websocket-aggregator", new WebSocketFrameAggregator(maxContentLength));

            // 5. 添加WebSocket协议处理器（处理握手和协议升级）
            String websocketPath = NetConfig.getInstance().getWebPath();
            pipeline.addLast("websocket-protocol", new WebSocketServerProtocolHandler(websocketPath));

            // 6. 添加业务处理器
            WebsocketServerHandler websocketServerHandler = new WebsocketServerHandler();
            pipeline.addLast("websocket-handler", websocketServerHandler);

            log.info("WebSocket连接初始化完成，处理器链就绪");
        } catch (Exception e) {
            log.error("WebSocket连接初始化失败", e);
            ctx.close(); // 初始化失败时关闭连接
            throw e; // 向上抛出异常，通知上层处理
        }
    }
}